<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class QuickLoginForm extends CFormModel
{
	public $username;

	private $_identity;

	public function rules()
	{
		return array(
			array('username','required',
				'message'=>Yii::t('app','Please enter a value for {attribute}.')),
			array('username','authenticate'),
			array('username','validateNotAdmin'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'username'=>Yii::t('label','Username'),
		);
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())
		{
			$this->_identity=new UserIdentity($this->username,null);
			if(!$this->_identity->authenticate())
				$this->addError('username',Yii::t('app','Incorrect username.'));
		}
	}

	/**
	 * Makes sure that admin never passes quick validation.
	 */
	public function validateNotAdmin($attribute,$params)
	{
		if(strtolower($this->username)==='admin')
			$this->addError('username',Yii::t('app','Incorrect username.'));
	}

	/**
	 * Logs in the user using the given username and password in the model.
	 * @return boolean whether login is successful
	 */
	public function login()
	{
		if($this->_identity===null)
		{
			$this->_identity=new UserIdentity($this->username,null);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
		{
			Yii::app()->user->login($this->_identity,0);
			return true;
		}
		else
			return false;
	}
}
